# 自动查找并启动 MySQL 服务

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "MySQL 服务启动助手" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""

# 查找所有 MySQL 相关服务
Write-Host "正在查找 MySQL 服务..." -ForegroundColor Yellow
$mysqlServices = Get-Service | Where-Object {
    $_.Name -like "*mysql*" -or 
    $_.DisplayName -like "*MySQL*" -or
    $_.DisplayName -like "*MariaDB*"
}

if ($mysqlServices) {
    Write-Host "找到以下 MySQL 相关服务：" -ForegroundColor Green
    $mysqlServices | Format-Table Name, Status, DisplayName -AutoSize
    
    foreach ($service in $mysqlServices) {
        Write-Host "`n检查服务: $($service.DisplayName) ($($service.Name))" -ForegroundColor Cyan
        Write-Host "  当前状态: $($service.Status)" -ForegroundColor White
        
        if ($service.Status -ne 'Running') {
            Write-Host "  正在启动服务..." -ForegroundColor Yellow
            try {
                Start-Service -Name $service.Name -ErrorAction Stop
                Write-Host "  ✓ 服务已成功启动！" -ForegroundColor Green
            }
            catch {
                Write-Host "  ✗ 启动失败: $_" -ForegroundColor Red
                Write-Host "  提示: 请右键点击 PowerShell，选择'以管理员身份运行'后再试" -ForegroundColor Yellow
            }
        }
        else {
            Write-Host "  ✓ 服务已在运行中" -ForegroundColor Green
        }
    }
}
else {
    Write-Host "未找到 MySQL 服务！" -ForegroundColor Red
    Write-Host ""
    Write-Host "可能的原因：" -ForegroundColor Yellow
    Write-Host "1. MySQL 未安装" -ForegroundColor White
    Write-Host "2. MySQL 服务名称不同" -ForegroundColor White
    Write-Host "3. MySQL 通过其他方式安装（XAMPP/WAMP/Laragon）" -ForegroundColor White
    Write-Host ""
    Write-Host "所有服务列表：" -ForegroundColor Cyan
    Get-Service | Select-Object -First 20 Name, Status, DisplayName | Format-Table -AutoSize
}

Write-Host ""
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "测试数据库连接..." -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan

$testResult = Test-NetConnection -ComputerName 127.0.0.1 -Port 3306 -InformationLevel Quiet -WarningAction SilentlyContinue

if ($testResult) {
    Write-Host "✓ MySQL 端口 3306 连接成功！" -ForegroundColor Green
    Write-Host ""
    Write-Host "现在可以运行迁移命令：" -ForegroundColor Cyan
    Write-Host "  php artisan migrate" -ForegroundColor Yellow
}
else {
    Write-Host "✗ MySQL 端口 3306 无法连接" -ForegroundColor Red
    Write-Host ""
    Write-Host "请尝试：" -ForegroundColor Yellow
    Write-Host "1. 检查 MySQL 是否真的在运行" -ForegroundColor White
    Write-Host "2. 检查防火墙设置" -ForegroundColor White
    Write-Host "3. 检查 MySQL 配置文件中的端口设置" -ForegroundColor White
}

Write-Host ""

